home *** CD-ROM | disk | FTP | other *** search
/ MacTech 1 to 12 / MacTech-vol-1-12.toast / Reference / FAQs on CD / C++ FAQ Lite (7⁄7) < prev    next >
Encoding:
Text File  |  1997-01-17  |  53.3 KB  |  1,372 lines  |  [TEXT/R*ch]

  1. Archive-name: C++-faq/part7
  2. Posting-Frequency: monthly
  3. Last-modified: Jan 1, 1997
  4. URL: http://www.cerfnet.com/~mpcline/c++-faq-lite/
  5.  
  6. AUTHOR: Marshall Cline / cline@parashift.com / Paradigm Shift, Inc. /
  7. One Park St. / Norwood, NY 13668 / 315-353-6100 (voice) / 315-353-6110 (fax)
  8.  
  9. COPYRIGHT: This posting is part of "C++ FAQ Lite."  The entire "C++ FAQ Lite"
  10. document is Copyright(C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com.
  11. All rights reserved.  Copying is permitted only under designated situations.
  12. For details, see section [1].
  13.  
  14. NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR PROVIDES NO
  15. WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING
  16. WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
  17. PURPOSE.
  18.  
  19. C++-FAQ-Lite != C++-FAQ-Book: This document, C++ FAQ Lite, is not the same as
  20. the C++ FAQ Book.  The book (C++ FAQs, Cline and Lomow, Addison-Wesley) is 500%
  21. larger than this document, and is available in bookstores.  For details, see
  22. section [3].
  23.  
  24. ==============================================================================
  25.  
  26. SECTION [29]: How to mix C and C++
  27.  
  28.  
  29. [29.1] What do I need to know when mixing C and C++ code?
  30.  
  31. There are several caveats:
  32.  * Your must use your C++ compiler when compiling main() (e.g., for static
  33.    initialization)
  34.  * Your C++ compiler should direct the linking process (e.g., so it can get its
  35.    special libraries)
  36.  * Your C and C++ compilers probably need to come from same vendor and have
  37.    compatible versions (e.g., so they have the same calling conventions)
  38.  
  39. In addition, you'll need to read the rest of this section to find out how to
  40. make your C functions callable by C++ and/or your C++ functions callable by C.
  41.  
  42. ==============================================================================
  43.  
  44. [29.2] How can I include a standard C header file in my C++ code?
  45.  
  46. To #include a standard header file (such as <stdio.h>), you don't have to do
  47. anything unusual.  E.g.,
  48.  
  49.     // This is C++ code
  50.  
  51.     #include <stdio.h>          // Note: nothing unusual in #include line
  52.  
  53.     main()
  54.     {
  55.       printf("Hello world\n");  // Note: nothing unusual in the call
  56.     }
  57.  
  58. Note: Somewhat different guidelines apply for non-system C headers.  There are
  59. two cases: either you can't change the header[29.3], or you can change the
  60. header[29.4].
  61.  
  62. ==============================================================================
  63.  
  64. [29.3] How can I include a non-system C header file in my C++ code?
  65.  
  66. If you are including a C header file that isn't provided by the system, you may
  67. need to wrap the #include line in an extern C { /*...*/ } construct.  This
  68. tells the C++ compiler that the functions declared in the header file are are C
  69. functions.
  70.  
  71.     // This is C++ code
  72.  
  73.     extern "C" {
  74.       // Get declaration for f(int i, char c, float x)
  75.       #include "my-C-code.h"
  76.     }
  77.  
  78.     main()
  79.     {
  80.       f(7, 'x', 3.14);   // Note: nothing unusual in the call
  81.     }
  82.  
  83. Note: Somewhat different guidelines apply for C headers provided by the system
  84. (such as <stdio.h>)[29.2] and for C headers that you can change[29.4].
  85.  
  86. ==============================================================================
  87.  
  88. [29.4] How can I modify my own C header files so it's easier to #include them
  89.        in C++ code?
  90.  
  91. If you are including a C header file that isn't provided by the system, and if
  92. you are able to change the C header, you should strongly consider adding the
  93. extern C {...} logic inside the header to make it easier for C++ users to
  94. #include it into their C++ code.  Since a C compiler won't understand the
  95. extern C construct, you must wrap the extern C { and } lines in an #ifdef so
  96. they won't be seen by normal C compilers.
  97.  
  98. Step #1: Put the following lines at the very top of your C header file (note:
  99. the symbol __cplusplus is #defined if/only-if the compiler is a C++ compiler):
  100.  
  101.     #ifdef __cplusplus
  102.     extern "C" {
  103.     #endif
  104.  
  105. Step #2: Put the following lines at the very bottom of your C header file:
  106.  
  107.     #ifdef __cplusplus
  108.     }
  109.     #endif
  110.  
  111. Now you can #include your C header without any extern C nonsense in your C++
  112. code:
  113.  
  114.     // This is C++ code
  115.  
  116.     // Get declaration for f(int i, char c, float x)
  117.     #include "my-C-code.h"   // Note: nothing unusual in #include line
  118.  
  119.     main()
  120.     {
  121.       f(7, 'x', 3.14);       // Note: nothing unusual in the call
  122.     }
  123.  
  124. Note: Somewhat different guidelines apply for C headers provided by the system
  125. (such as <stdio.h>)[29.2] and for C headers that you can't change[29.3].
  126.  
  127. ==============================================================================
  128.  
  129. [29.5] How can I call a non-system C function f(int,char,float) from my C++
  130.        code?
  131.  
  132. If you have an individual C function that you want to call, and for some reason
  133. you don't have or don't want to #include a C header file in which that function
  134. is declared, you can declare the individual C function in your C code using the
  135. extern C syntax.  Naturally you need to use the full function prototype:
  136.  
  137.     extern "C" void f(int i, char c, float x);
  138.  
  139. A block of several C functions can be grouped via braces:
  140.  
  141.     extern "C" {
  142.       void   f(int i, char c, float x);
  143.       int    g(char* s, const char* s2);
  144.       double sqrtOfSumOfSquares(double a, double b);
  145.     }
  146.  
  147. After this you simply call the function just as if it was a C++ function:
  148.  
  149.     main()
  150.     {
  151.       f(7, 'x', 3.14);   // Note: nothing unusual in the call
  152.     }
  153.  
  154. ==============================================================================
  155.  
  156. [29.6] How can I create a C++ function f(int,char,float) that is callable by my
  157.        C code?
  158.  
  159. The C++ compiler must know that f(int,char,float) is to be called by a C
  160. compiler using the extern C construct[29.3]:
  161.  
  162.     // This is C++ code
  163.  
  164.     // Declare f(int,char,float) using extern C:
  165.     extern "C" void f(int i, char c, float x);
  166.  
  167.     // ...
  168.  
  169.     // Define f(int,char,float) in some C++ module:
  170.     void f(int i, char c, float x)
  171.     {
  172.       // ...
  173.     }
  174.  
  175. The extern C line tells the compiler that the external information sent to the
  176. linker should use C calling conventions and name mangling (e.g., preceded by a
  177. single underscore).  Since name overloading isn't supported by C, you can't
  178. make several overloaded functions simultaneously callable by a C program.
  179.  
  180. ==============================================================================
  181.  
  182. [29.7] Why is the linker giving errors for C/C++ functions being called from
  183.        C++/C functions?
  184.  
  185. If you didn't get your extern C right, you'll sometimes get linker errors
  186. rather than compiler errors.  This is due to the fact that C++ compilers
  187. usually "mangle" function names (e.g., to support function overloading)
  188. differently than C compilers.
  189.  
  190. See the previous two FAQs on how to use extern C.
  191.  
  192. ==============================================================================
  193.  
  194. [29.8] How can I pass an object of a C++ class to/from a C function? [UPDATED!]
  195.  
  196. [Recently added #ifndef FRED_H / #define FRED_H to code (on 1/97).]
  197.  
  198. Here's an example (for info on extern C, see the previous two FAQs).
  199.  
  200. Fred.h:
  201.  
  202.     /* This header can be read by both C and C++ compilers */
  203.     #ifndef FRED_H
  204.     #define FRED_H
  205.  
  206.     #ifdef __cplusplus
  207.       class Fred {
  208.       public:
  209.         Fred();
  210.         void wilma(int);
  211.       private:
  212.         int a_;
  213.       };
  214.     #else
  215.       typedef
  216.         struct Fred
  217.           Fred;
  218.     #endif
  219.  
  220.     #ifdef __cplusplus
  221.     extern "C" {
  222.     #endif
  223.  
  224.     #if defined(__STDC__) || defined(__cplusplus)
  225.       extern void c_function(Fred*);   /* ANSI-C prototypes */
  226.       extern Fred* cplusplus_callback_function(Fred*);
  227.     #else
  228.       extern void c_function();        /* K&R style */
  229.       extern Fred* cplusplus_callback_function();
  230.     #endif
  231.  
  232.     #ifdef __cplusplus
  233.     }
  234.     #endif
  235.  
  236.     #endif /*FRED_H*/
  237.  
  238. Fred.cpp:
  239.  
  240.     // This is C++ code
  241.  
  242.     #include "Fred.h"
  243.  
  244.     Fred::Fred() : a_(0) { }
  245.  
  246.     void Fred::wilma(int a) { }
  247.  
  248.     Fred* cplusplus_callback_function(Fred* fred)
  249.     {
  250.       fred->wilma(123);
  251.       return fred;
  252.     }
  253.  
  254. main.cpp:
  255.  
  256.     // This is C++ code
  257.  
  258.     #include "Fred.h"
  259.  
  260.     int main()
  261.     {
  262.       Fred fred;
  263.       c_function(&fred);
  264.       return 0;
  265.     }
  266.  
  267. c-function.c:
  268.  
  269.     /* This is C code */
  270.  
  271.     #include "Fred.h"
  272.  
  273.     void c_function(Fred* fred)
  274.     {
  275.       cplusplus_callback_function(fred);
  276.     }
  277.  
  278. Passing pointers to C++ objects to/from C functions will fail if you pass and
  279. get back something that isn't exactly the same pointer.  For example, don't
  280. pass a base class pointer and receive back a derived class pointer, since your
  281. C compiler won't understand the pointer conversions necessary to handle
  282. multiple and/or virtual inheritance.
  283.  
  284. ==============================================================================
  285.  
  286. [29.9] Can my C function directly access data in an object of a C++ class?
  287.  
  288. Sometimes.
  289.  
  290. (For basic info on passing C++ objects to/from C functions, read the previous
  291. FAQ).
  292.  
  293. You can safely access a C++ object's data from a C function if the C++ class:
  294.  * Has no virtual[20] functions (including inherited virtual functions)
  295.  * Has all its data in the same access-level section (private/protected/public)
  296.  * Has no fully-contained subobjects with virtual[20] functions
  297.  
  298. If the C++ class has any base classes at all (or if any fully contained
  299. subobjects have base classes), accessing the data will technically be
  300. non-portable, since class layout under inheritance isn't imposed by the
  301. language.  However in practice, all C++ compilers do it the same way: the base
  302. class object appears first (in left-to-right order in the event of multiple
  303. inheritance), and member objects follow.
  304.  
  305. Furthermore, if the class (or any base class) contains any virtual functions,
  306. almost all C++ compliers put a void* into the object either at the location of
  307. the first virtual function or at the very beginning of the object.  Again, this
  308. is not required by the language, but it is the way "everyone" does it.
  309.  
  310. If the class has any virtual base classes, it is even more complicated and less
  311. portable.  One common implementation technique is for objects to contain an
  312. object of the virtual base class (V) last (regardless of where V shows up as a
  313. virtual base class in the inheritance hierarchy).  The rest of the object's
  314. parts appear in the normal order.  Every derived class that has V as a virtual
  315. base class actually has a pointer to the V part of the final object.
  316.  
  317. ==============================================================================
  318.  
  319. [29.10] Why do I feel like I'm "further from the machine" in C++ as opposed to
  320.         C?
  321.  
  322. Because you are.
  323.  
  324. As an OO programming language, C++ allows you to model the problem domain
  325. itself, which allows you to program in the language of the problem domain
  326. rather than in the language of the solution domain.
  327.  
  328. One of C's great strengths is the fact that it has "no hidden mechanism": what
  329. you see is what you get.  You can read a C program and "see" every clock cycle.
  330. This is not the case in C++; old line C programmers (such as many of us once
  331. were) are often ambivalent (can you say, "hostile"?) about this feature.
  332. However after they've made the transition to OO thinking, they often realize
  333. that although C++ hides some mechanism from the programmer, it also provides a
  334. level of abstraction and economy of expression which lowers maintenance costs
  335. without destroying run-time performance.
  336.  
  337. Naturally you can write bad code in any language; C++ doesn't guarantee any
  338. particular level of quality, reusability, abstraction, or any other measure of
  339. "goodness."
  340.  
  341. C++ doesn't try to make it impossible for bad programmers to write bad
  342. programs; it enables reasonable developers to create superior software.
  343.  
  344. ==============================================================================
  345.  
  346. SECTION [30]: Pointers to member functions
  347.  
  348.  
  349. [30.1] Is the type of "pointer-to-member-function" different from
  350.        "pointer-to-function"?
  351.  
  352. Yep.
  353.  
  354. Consider the following function:
  355.  
  356.     int f(char a, float b);
  357.  
  358. The type of this function is different depending on whether it is an ordinary
  359. function or a non-static member function of some class:
  360.  * It's type is "int (*)(char,float)" if an ordinary function
  361.  * It's type is "int (Fred::*)(char,float)" if a non-static member function of
  362.    class Fred
  363.  
  364. Note: if it's a static member function of class Fred, its type is the same as
  365. if it was an ordinary function: "int (*)(char,float)".
  366.  
  367. ==============================================================================
  368.  
  369. [30.2] How do I pass a pointer to member function to a signal handler, X event
  370.        callback, etc?
  371.  
  372. Don't.
  373.  
  374. Because a member function is meaningless without an object to invoke it on, you
  375. can't do this directly (if The X Windows System was rewritten in C++, it would
  376. probably pass references to objects around, not just pointers to functions;
  377. naturally the objects would embody the required function and probably a whole
  378. lot more).
  379.  
  380. As a patch for existing software, use a top-level (non-member) function as a
  381. wrapper which takes an object obtained through some other technique (held in a
  382. global, perhaps).  The top-level function would apply the desired member
  383. function against the global object.
  384.  
  385. E.g., suppose you want to call Fred::memberFunction() on interrupt:
  386.  
  387.     class Fred {
  388.     public:
  389.       void memberFunction();
  390.       static void staticMemberFunction();  // A static member function can handle it
  391.       // ...
  392.     };
  393.  
  394.     // Wrapper function uses a global to remember the object:
  395.     Fred* object_which_will_handle_signal;
  396.     void Fred_memberFunction_wrapper()
  397.     {
  398.       object_which_will_handle_signal->memberFunction();
  399.     }
  400.  
  401.     main()
  402.     {
  403.       /* signal(SIGINT, Fred::memberFunction); */   // Can NOT do this
  404.       signal(SIGINT, Fred_memberFunction_wrapper);  // OK
  405.       signal(SIGINT, Fred::staticMemberFunction);   // Also OK
  406.     }
  407.  
  408. Note: static member functions do not require an actual object to be invoked, so
  409. pointers-to-static-member-functions are type compatible with regular
  410. pointers-to-functions.
  411.  
  412. ==============================================================================
  413.  
  414. [30.3] Why do I keep getting compile errors (type mismatch) when I try to use a
  415.        member function as an interrupt service routine?
  416.  
  417. This is a special case of the previous two questions, therefore read the
  418. previous two answers first.
  419.  
  420. Non-static member functions have a hidden parameter that corresponds to the
  421. this pointer.  The this pointer points to the instance data for the object.
  422. The interrupt hardware/firmware in the system is not capable of providing the
  423. this pointer argument.  You must use "normal" functions (non class members) or
  424. static member functions as interrupt service routines.
  425.  
  426. One possible solution is to use a static member as the interrupt service
  427. routine and have that function look somewhere to find the instance/member pair
  428. that should be called on interrupt.  Thus the effect is that a member function
  429. is invoked on an interrupt, but for technical reasons you need to call an
  430. intermediate function first.
  431.  
  432. ==============================================================================
  433.  
  434. [30.4] Why am I having trouble taking the address of a C++ function?
  435.  
  436. This is a corollary to the previous FAQ.
  437.  
  438. Long answer: In C++, member functions have an implicit parameter which points
  439. to the object (the this pointer inside the member function).  Normal C
  440. functions can be thought of as having a different calling convention from
  441. member functions, so the types of their pointers (pointer-to-member-function
  442. vs. pointer-to-function) are different and incompatible.  C++ introduces a new
  443. type of pointer, called a pointer-to-member, which can be invoked only by
  444. providing an object.
  445.  
  446. NOTE: do not attempt to "cast" a pointer-to-member-function into a
  447. pointer-to-function; the result is undefined and probably disastrous.  E.g., a
  448. pointer-to-member-function is not required to contain the machine address of
  449. the appropriate function.  As was said in the last example, if you have a
  450. pointer to a regular C function, use either a top-level (non-member) function,
  451. or a static (class) member function.
  452.  
  453. ==============================================================================
  454.  
  455. [30.5] How can I avoid syntax errors when calling a member function using a
  456.        pointer-to-member-function?
  457.  
  458. Two things: (1) use a typedef, and (2) use a #define macro.
  459.  
  460. Here's the way you create the typedef:
  461.  
  462.     class Fred {
  463.     public:
  464.       int f(char x, float y);
  465.       int g(char x, float y);
  466.       int h(char x, float y);
  467.       int i(char x, float y);
  468.       // ...
  469.     };
  470.  
  471.     // FredMemberFn points to a member of Fred that takes (char,float)
  472.     typedef  int (Fred::*FredMemberFn)(char x, float y);
  473.  
  474. Here's the way you create the #define macro (normally I dislike #define
  475. macros[9.3], but this is one of those rare cases where they actually improve
  476. the readability and writability of your code):
  477.  
  478.     #define callMemberFunction(object,ptrToMember)  ((object).*(ptrToMember))
  479.  
  480. Here's how you use these features:
  481.  
  482.     void userCode(Fred& fred, FredMemberFn memFn)
  483.     {
  484.       callMemberFunction(fred,memFn)('x', 3.14);
  485.       // Would normally be: (fred.*memFn)('x', 3.14);
  486.     }
  487.  
  488. I strongly recommend these features.  In the real world, member function
  489. invocations are a lot more complex than the simple example just given, and the
  490. difference in readability and writability is significant.  comp.lang.c++ has
  491. had to endure hundreds and hundreds of postings from confused programmers who
  492. couldn't quite get the syntax right.  Almost all these errors would have
  493. vanished had they used these features.
  494.  
  495. ==============================================================================
  496.  
  497. [30.6] How do I create and use an array of pointers to member functions?
  498.  
  499. Use the usual typedef and #define macro[30.5] and you're 90% done.
  500.  
  501. First, use a typedef:
  502.  
  503.     class Fred {
  504.     public:
  505.       int f(char x, float y);
  506.       int g(char x, float y);
  507.       int h(char x, float y);
  508.       int i(char x, float y);
  509.       // ...
  510.     };
  511.  
  512.     // FredMemberFn points to a member of Fred that takes (char,float)
  513.     typedef  int (Fred::*FredMemberFn)(char x, float y);
  514.  
  515. That makes the array of pointers-to-member-functions straightforward:
  516.  
  517.     FredMemberFn a[4] = { &Fred::f, &Fred::g, &Fred::h, &Fred::i };
  518.  
  519. Second, use the callMemberFunction macro:
  520.  
  521.     #define callMemberFunction(object,ptrToMember)  ((object).*(ptrToMember))
  522.  
  523. That makes calling one of the member functions on object "fred"
  524. straightforward:
  525.  
  526.     void userCode(Fred& fred, int memberFunctionNum)
  527.     {
  528.       // Assume memberFunctionNum is between 0 and 3 inclusive:
  529.       callMemberFunction(fred, a[memberFunctionNum]) ('x', 3.14);
  530.     }
  531.  
  532. ==============================================================================
  533.  
  534. SECTION [31]: Container classes and templates
  535.  
  536.  
  537. [31.1] How can I make a perl-like associative array in C++?
  538.  
  539. Use the standard class template map<Key,Val>:
  540.  
  541.     #include <string>
  542.     #include <map>
  543.     #include <iostream>
  544.     using namespace std;
  545.  
  546.     main()
  547.     {
  548.       map<string,int,less<string> >  age;   // age is a map from string to int
  549.  
  550.       age["Fred"] = 42;                     // Fred is 42 years old
  551.       age["Barney"] = 37;                   // Barney is 37
  552.  
  553.       if (todayIsFredsBirthday())           // On Fred's birthday,
  554.         ++ age["Fred"];                     // increment Fred's age
  555.  
  556.       cout << "Fred is " << age["Fred"] << " years old\n";
  557.     }
  558.  
  559. ==============================================================================
  560.  
  561. [31.2] How can I build a <favorite container> of objects of different types?
  562.  
  563. You can't, but you can fake it pretty well.  In C/C++ all arrays are
  564. homogeneous (i.e., the elements are all the same type).  However, with an extra
  565. layer of indirection you can give the appearance of a heterogeneous container
  566. (a heterogeneous container is a container where the contained objects are of
  567. different types).
  568.  
  569. There are two cases with heterogeneous containers.
  570.  
  571. The first case occurs when all objects you want to store in a container are
  572. publicly derived from a common base class.  You can then declare/define your
  573. container to hold pointers to the base class.  You indirectly store a derived
  574. class object in a container by storing the object's address as an element in
  575. the container.  You can then access objects in the container indirectly through
  576. the pointers (enjoying polymorphic behavior).  If you need to know the exact
  577. type of the object in the container you can use dynamic_cast<> or typeid().
  578. You'll probably need the Virtual Constructor Idiom[20.5] to copy a container of
  579. disparate object types.  The downside of this approach is that it makes memory
  580. management a little more problematic (who "owns" the pointed-to objects? if you
  581. delete these pointed-to objects when you destroy the container, how can you
  582. guarantee that no one else has a copy of one of these pointers? if you don't
  583. delete these pointed-to objects when you destroy the container, how can you be
  584. sure that someone else will eventually do the deleteing?).  It also makes
  585. copying the container more complex (may actually break the container's copying
  586. functions since you don't want to copy the pointers, at least not when the
  587. container "owns" the pointed-to objects).
  588.  
  589. The second case occurs when the object types are disjoint -- they do not share
  590. a common base class.  The approach here is to use a handle class.  The
  591. container is a container of handle objects (by value or by pointer, your
  592. choice; by value is easier).  Each handle object knows how to "hold on to"
  593. (i.e. ,maintain a pointer to) one of the objects you want to put in the
  594. container.  You can use either a single handle class with several different
  595. types of pointers as instance data, or a hierarchy of handle classes that
  596. shadow the various types you wish to contain (requires the container be of
  597. handle base class pointers).  The downside of this approach is that it opens up
  598. the handle class(es) to maintenance every time you change the set of types that
  599. can be contained.  The benefit is that you can use the handle class(es) to
  600. encapsulate most of the ugliness of memory management and object lifetime.
  601. Thus using handle objects may be beneficial even in the first case.
  602.  
  603. ==============================================================================
  604.  
  605. [31.3] How can I insert/access/change elements from a linked
  606.        list/hashtable/etc?
  607.  
  608. I'll use an "inserting into a linked list" as a prototypical example.  It's
  609. easy to allow insertion at the head and tail of the list, but limiting
  610. ourselves to these would produce a library that is too weak (a weak library is
  611. almost worse than no library).
  612.  
  613. This answer will be a lot to swallow for novice C++'ers, so I'll give a couple
  614. of options.  The first option is easiest; the second and third are better.
  615.  
  616.  1. Empower the List with a "current location," and member functions such as
  617.     advance(), backup(), atEnd(), atBegin(), getCurrElem(), setCurrElem(Elem),
  618.     insertElem(Elem), and removeElem().  Although this works in small examples,
  619.     the notion of a current position makes it difficult to access elements at
  620.     two or more positions within the list (e.g., "for all pairs x,y do the
  621.     following...").
  622.  
  623.  2. Remove the above member functions from List itself, and move them to a
  624.     separate class, ListPosition.  ListPosition would act as a "current
  625.     position" within a list.  This allows multiple positions within the same
  626.     list.  ListPosition would be a friend[14] of class List, so List can hide
  627.     its innards from the outside world (else the innards of List would have to
  628.     be publicized via public member functions in List).  Note: ListPosition can
  629.     use operator overloading for things like advance() and backup(), since
  630.     operator overloading is syntactic sugar for normal member functions.
  631.  
  632.  3. Consider the entire iteration as an atomic event, and create a class
  633.     template to embodies this event.  This enhances performance by allowing the
  634.     public access member functions (which may be virtual[20] functions) to be
  635.     avoided during the inner loop.  Unfortunately you get extra object code in
  636.     the application, since templates gain speed by duplicating code.  For more,
  637.     see [Koenig, "Templates as interfaces," JOOP, 4, 5 (Sept 91)], and
  638.     [Stroustrup, "The C++ Programming Language Second Edition," under
  639.     "Comparator"].
  640.  
  641. ==============================================================================
  642.  
  643. [31.4] What's the idea behind templates?
  644.  
  645. A template is a cookie-cutter that specifies how to cut cookies that all look
  646. pretty much the same (although the cookies can be made of various kinds of
  647. dough, they'll all have the same basic shape).  In the same way, a class
  648. template is a cookie cutter for a description of how to build a family of
  649. classes that all look basically the same, and a function template describes how
  650. to build a family of similar looking functions.
  651.  
  652. Class templates are often used to build type safe containers (although this
  653. only scratches the surface for how they can be used).
  654.  
  655. ==============================================================================
  656.  
  657. [31.5] What's the syntax / semantics for a "function template"?
  658.  
  659. Consider this function that swaps its two integer arguments:
  660.  
  661.     void swap(int& x, int& y)
  662.     {
  663.       int tmp = x;
  664.       x = y;
  665.       y = tmp;
  666.     }
  667.  
  668. If we also had to swap floats, longs, Strings, Sets, and FileSystems, we'd get
  669. pretty tired of coding lines that look almost identical except for the type.
  670. Mindless repetition is an ideal job for a computer, hence a function template:
  671.  
  672.     template<class T>
  673.     void swap(T& x, T& y)
  674.     {
  675.       T tmp = x;
  676.       x = y;
  677.       y = tmp;
  678.     }
  679.  
  680. Every time we used swap() with a given pair of types, the compiler will go to
  681. the above definition and will create yet another "template function" as an
  682. instantiation of the above.  E.g.,
  683.  
  684.     main()
  685.     {
  686.       int    i,j;  /*...*/  swap(i,j);  // Instantiates a swap for int
  687.       float  a,b;  /*...*/  swap(a,b);  // Instantiates a swap for float
  688.       char   c,d;  /*...*/  swap(c,d);  // Instantiates a swap for char
  689.       String s,t;  /*...*/  swap(s,t);  // Instantiates a swap for String
  690.     }
  691.  
  692. Note: A "template function" is the instantiation of a "function template".
  693.  
  694. ==============================================================================
  695.  
  696. [31.6] What's the syntax / semantics for a "class template"?
  697.  
  698. Consider a container class Array that acts like an array of integers:
  699.  
  700.     // This would go into a header file such as "Array.h"
  701.     class Array {
  702.     public:
  703.       Array(int len=10)                  : len_(len), data_(new int[len]) { }
  704.      ~Array()                            { delete [] data_; }
  705.       int len() const                    { return len_;     }
  706.       const int& operator[](int i) const { return data_[check(i)]; }
  707.             int& operator[](int i)       { return data_[check(i)]; }
  708.       Array(const Array&);
  709.       Array& operator= (const Array&);
  710.     private:
  711.       int  len_;
  712.       int* data_;
  713.       int  check(int i) const
  714.         { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
  715.           return i; }
  716.     };
  717.  
  718. Just as with swap() above, repeating the above over and over for Array of
  719. float, of char, of String, of Array-of-String, etc, will become tedious.
  720.  
  721.     // This would go into a header file such as "Array.h"
  722.     template<class T>
  723.     class Array {
  724.     public:
  725.       Array(int len=10)                : len_(len), data_(new T[len]) { }
  726.      ~Array()                          { delete [] data_; }
  727.       int len() const                  { return len_;     }
  728.       const T& operator[](int i) const { return data_[check(i)]; }
  729.             T& operator[](int i)       { return data_[check(i)]; }
  730.       Array(const Array<T>&);
  731.       Array<T>& operator= (const Array<T>&);
  732.     private:
  733.       int len_;
  734.       T*  data_;
  735.       int check(int i) const
  736.         { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
  737.           return i; }
  738.     };
  739.  
  740. Unlike template functions, template classes (instantiations of class templates)
  741. need to be explicit about the parameters over which they are instantiating:
  742.  
  743.     main()
  744.     {
  745.       Array<int>           ai;
  746.       Array<float>         af;
  747.       Array<char*>         ac;
  748.       Array<String>        as;
  749.       Array< Array<int> >  aai;
  750.     }
  751.  
  752. Note the space between the two >'s in the last example.  Without this space,
  753. the compiler would see a >> (right-shift) token instead of two >'s.
  754.  
  755. ==============================================================================
  756.  
  757. [31.7] What is a "parameterized type"?
  758.  
  759. Another way to say, "class templates."
  760.  
  761. A parameterized type is a type that is parameterized over another type or some
  762. value.  List<int> is a type (List) parameterized over another type (int).
  763.  
  764. ==============================================================================
  765.  
  766. [31.8] What is "genericity"?
  767.  
  768. Yet another way to say, "class templates."
  769.  
  770. Not to be confused with "generality" (which just means avoiding solutions which
  771. are overly specific), "genericity" means class templates.
  772.  
  773. ==============================================================================
  774.  
  775. SECTION [32]: Class libraries
  776.  
  777.  
  778. [32.1] Where can I get a copy of "STL"?
  779.  
  780. "STL" is the "Standard Templates Library".  You can get a copy from:
  781.  * An STL site: ftp://ftp.cs.rpi.edu/pub/stl
  782.  * STL HP official site: ftp://butler.hpl.hp.com/stl/
  783.  * Mirror site in Europe: http://www.maths.warwick.ac.uk/ftp/mirrors/c++/stl/
  784.  * STL code alternate: ftp://ftp.cs.rpi.edu/stl
  785.  * STL code + examples: http://www.cs.rpi.edu/~musser/stl.html
  786.  
  787. STL hacks for GCC-2.6.3 are part of the GNU libg++ package 2.6.2.1 or later
  788. (and they may be in an earlier version as well).  Thanks to Mike Lindner.
  789.  
  790. ==============================================================================
  791.  
  792. [32.2] How can I find a Fred object in an STL container of Fred* such as
  793.        vector<Fred*>?
  794.  
  795. STL functions such as std::find_if() help you find a T element in a container
  796. of T's.  But if you have a container of pointers such as vector<Fred*>, these
  797. functions will enable you to find an element that matches a given Fred*
  798. pointer, but they don't let you find an element that matches a given Fred
  799. object.
  800.  
  801. The solution is to use an optional parameter that specifies the "match"
  802. function.  The following class template lets you compare the objects on the
  803. other end of the dereferenced pointers.
  804.  
  805.     template<class T>
  806.     class DereferencedEqual {
  807.     public:
  808.       DereferencedEqual(const T* p) : p_(p) { }
  809.       bool operator== (const T* p2) const { return *p == *p2; }
  810.     private:
  811.       const T* p_;
  812.     };
  813.  
  814. Now you can use this template to find an appropriate Fred object:
  815.  
  816.     void userCode(vector<Fred*> v, const Fred& match)
  817.     {
  818.       find_if(v.begin(), v.end(), DereferencedEqual<Fred>(&match));
  819.       // ...
  820.     }
  821.  
  822. ==============================================================================
  823.  
  824. [32.3] Where can I get help on how to use STL?
  825.  
  826. Kenny Zalewski's STL guide: http://www.cs.rpi.edu/projects/STL/htdocs/stl.html
  827.  
  828. Dave Musser's STL guide: http://www.cs.rpi.edu/~musser/stl.html
  829.  
  830. Mumit's STL Newbie's guide:
  831. http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html
  832.  
  833. ==============================================================================
  834.  
  835. [32.4] How can you tell if you have a dynamically typed C++ class library?
  836.  
  837.  * Hint #1: when everything is derived from a single root class, usually
  838.    Object.
  839.  * Hint #2: when the container classes (List, Stack, Set, etc) are
  840.    non-templates.
  841.  * Hint #3: when the container classes (List, Stack, Set, etc) insert/extract
  842.    elements as pointers to Object.  This lets you put an Apple into such a
  843.    container, but when you get it out, the compiler knows only that it is
  844.    derived from Object, so you have to use a pointer cast to convert it back to
  845.    an Apple*; and you better pray a lot that it really is an Apple, cause your
  846.    blood is on your own head).
  847.  
  848. You can make the pointer cast "safe" by using dynamic_cast, but this dynamic
  849. testing is just that: dynamic.  This coding style is the essence of dynamic
  850. typing in C++.  You call a function that says "convert this Object into an
  851. Apple or give me NULL if its not an Apple," and you've got dynamic typing: you
  852. don't know what will happen until run-time.
  853.  
  854. When you use templates to implement your containers, the C++ compiler can
  855. statically validate 90+% of an application's typing information (the figure
  856. "90+%" is apocryphal; some claim they always get 100%, those who need
  857. persistence[34.4] get something less than 100% static type checking).  The
  858. point is: C++ gets genericity from templates, not from inheritance.
  859.  
  860. ==============================================================================
  861.  
  862. [32.5] What is the NIHCL? Where can I get it?
  863.  
  864. NIHCL stands for "National-Institute-of-Health's-class-library." It can be
  865. acquired via ftp://128.231.128.7/pub/NIHCL/nihcl-3.0.tar.Z
  866.  
  867. NIHCL (some people pronounce it "N-I-H-C-L," others pronounce it like "nickel")
  868. is a C++ translation of the Smalltalk class library[32.4].  There are some ways
  869. where NIHCL's use of dynamic typing helps (e.g., persistent[34.4] objects).
  870. There are also places where its use of dynamic typing creates tension[27.3]
  871. with the static typing of the C++ language.
  872.  
  873. ==============================================================================
  874.  
  875. [32.6] Where can I ftp the code that accompanies "Numerical Recipes"?
  876.  
  877. This software is sold and therefore it would be illegal to provide it on the
  878. net.  However, it's only about $30.
  879.  
  880. ==============================================================================
  881.  
  882. [32.7] Why is my executable so large?
  883.  
  884. Many people are surprised by how big executables are, especially if the source
  885. code is trivial.  For example, a simple "hello world" program can generate an
  886. executable that is larger than most people expect (40+K bytes).
  887.  
  888. One reason executables can be large is that portions of the C++ runtime library
  889. gets linked with your program. How much gets linked in depends on how much of
  890. it you are using, and on how the implementer split up the library into pieces.
  891. For example, the <iostream.h> library is quite large, and consists of numerous
  892. classes and virtual[20] functions.  Using any part of it might pull in nearly
  893. all of the <iostream.h> code as a result of the interdependencies.
  894.  
  895. You might be able to make your program smaller by using a dynamically-linked
  896. version of the library instead of the static version.
  897.  
  898. You have to consult your compiler manuals or the vendor's technical support for
  899. a more detailed answer.
  900.  
  901. ==============================================================================
  902.  
  903. [32.8] Where can I get tons and tons of more information on C++ class
  904.        libraries?
  905.  
  906. The C++ Libraries FAQ is maintained by Nikki Locke cpplibs@trmphrst.demon.co.uk
  907. and is available at http://www.trmphrst.demon.co.uk/cpplibs1.html
  908.  
  909. ==============================================================================
  910.  
  911. SECTION [33]: Compiler dependencies
  912.  
  913.  
  914. [33.1] How do I display text in the status bar using MFC? [NEW!]
  915.  
  916. [Recently created with the help of Paul Ganney (on 11/96).]
  917.  
  918. Use the following code snipped:
  919.  
  920.     CString s = "Text";
  921.     CStatusBar* p =
  922.      (CStatusBar*)AfxGetApp()->m_pMainWnd->GetDescendantWindow(AFX_IDW_STATUS_BAR);
  923.     p->SetPaneText(1, s);
  924.  
  925. This works with MFC v.1.00 which hopefully means it will work with other
  926. versions as well.
  927.  
  928. ==============================================================================
  929.  
  930. [33.2] How can I decompile an executable program back into C++ source code?
  931.  
  932. You gotta be kidding, right?
  933.  
  934. Here are a few of the many reasons this is not even remotely feasible:
  935.  * What makes you think the program was written in C++ to begin with?
  936.  * Even if you are sure it was originally written (at least partially) in C++,
  937.    which one of the gazillion C++ compilers produced it?
  938.  * Even if you know the compiler, which particular version of the compiler was
  939.    used?
  940.  * Even if you know the compiler's manufacturer and version number, what
  941.    compile-time options were used?
  942.  * Even if you know the compiler's manufacturer and version number and
  943.    compile-time options, what third party libraries were linked-in, and what
  944.    was their version?
  945.  * Even if you know all that stuff, most executables have had their debugging
  946.    information stripped out, so the resulting decompiled code will be totally
  947.    unreadable.
  948.  * Even if you know everything about the compiler, manufacturer, version
  949.    number, compile-time options, third party libraries, and debugging
  950.    information, the cost of writing a decompiler that works with even one
  951.    particular compiler and has even a modest success rate at generating code
  952.    would be a monumental effort -- on the par with writing the compiler itself
  953.    from scratch.
  954.  
  955. But the biggest question is not how you can decompile someone's code, but why
  956. do you want to do this? If you're trying to reverse-engineer someone elses
  957. code, shame on you; go find honest work.  If you're trying to recover from
  958. losing your own source, the best suggestion I have is to make better backups
  959. next time.
  960.  
  961. ==============================================================================
  962.  
  963. [33.3] Where can I get information about the C++ compiler from {Borland, IBM,
  964.        Microsoft, Semantic, Sun, etc.}? [UPDATED!]
  965.  
  966. [Recently added HP C++ (on 1/97).]
  967.  
  968. In alphabetical order by vendor name:
  969.  * Borland C++ 5.0 FAQs: http://www.mdex.net/~kentr/bc50faq.htm
  970.  * HP C++: [please let me know; thanks; (cline@parashift.com)]
  971.  * IBM VisualAge C++: http://www.software.ibm.com/ad/cset/
  972.  * Metrowerks C++: http://metrowerks.com or http://www.metrowerks.com
  973.  * Microsoft Visual C++: a tutorial [please let me know about other links;
  974.    thanks; (cline@parashift.com)]
  975.  * Silicon Graphics C++:
  976.    http://www.sgi.com/Products/DevMagic/products/cplusplus.html
  977.  * Sun C++: [please let me know; thanks; (cline@parashift.com)]
  978.  * Symantec C++: http://www.symantec.com/lit/dev/
  979.  * Watcom C++: http://www.powersoft.com/products/languages/watccpl.html
  980.  
  981. [If anyone has other suggestions that should go into this list, please let me
  982. know; thanks; (cline@parashift.com)].
  983.  
  984. ==============================================================================
  985.  
  986. [33.4] How do compilers use "over-allocation" to remember the number of
  987.        elements in an allocated array?
  988.  
  989. Recall that when you delete[] an array, the runtime system magically knows how
  990. many destructors to run[16.13].  This FAQ describes a technique used by some
  991. C++ compilers to do this (the other common technique is to use an associative
  992. array[33.5]).
  993.  
  994. If the compiler uses the "over-allocation" technique, the code for
  995. p = new Fred[n] looks something like the following.  Note that WORDSIZE is an
  996. imaginary machine-dependent constant that is at least sizeof(size_t), possibly
  997. rounded up for any alignment constraints.  On many machines, this constant will
  998. have a value of 4 or 8.  It is not a real C++ identifier that will be defined
  999. for your compiler.
  1000.  
  1001.     // Original code: Fred* p = new Fred[n];
  1002.     char* tmp = (char*) operator new[] (WORDSIZE + n * sizeof(Fred));
  1003.     Fred* p = (Fred*) (tmp + WORDSIZE);
  1004.     *(size_t*)tmp = n;
  1005.     size_t i;
  1006.     try {
  1007.       for (i = 0; i < n; ++i)
  1008.         new(p + i) Fred();           // Placement new[11.10]
  1009.     } catch (...) {
  1010.       while (i-- != 0)
  1011.         (p + i)->~Fred();            // Explicit call to the destructor[11.10]
  1012.       operator delete[] ((char*)p - WORDSIZE);
  1013.       throw;
  1014.     }
  1015.  
  1016. Then the delete[] p statement becomes:
  1017.  
  1018.     // Original code: delete[] p;
  1019.     size_t n = * (size_t*) ((char*)p - WORDSIZE);
  1020.     while (n-- != 0)
  1021.       (p + n)->~Fred();
  1022.     operator delete[] ((char*)p - WORDSIZE);
  1023.  
  1024. Note that the address passed to operator delete[] is not the same as p.
  1025.  
  1026. Compared to the associative array technique[33.5], this technique is faster,
  1027. but more sensitive to the problem of programmers saying delete p rather than
  1028. delete[] p.  For example, if you make a programming error by saying delete p
  1029. where you should have said delete[] p, the address that is passed to
  1030. operator delete(void*) is not the address of any valid heap allocation.  This
  1031. will probably corrupt the heap.  Bang! You're dead!
  1032.  
  1033. ==============================================================================
  1034.  
  1035. [33.5] How do compilers use an "associative array" to remember the number of
  1036.        elements in an allocated array?
  1037.  
  1038. Recall that when you delete[] an array, the runtime system magically knows how
  1039. many destructors to run[16.13].  This FAQ describes a technique used by some
  1040. C++ compilers to do this (the other common technique is to
  1041. over-allocate[33.4]).
  1042.  
  1043. If the compiler uses the associative array technique, the code for
  1044. p = new Fred[n] looks something like this (where arrayLengthAssociation is the
  1045. imaginary name of a hidden, global associative array that maps from void* to
  1046. "size_t"):
  1047.  
  1048.     // Original code: Fred* p = new Fred[n];
  1049.     Fred* p = (Fred*) operator new[] (n * sizeof(Fred));
  1050.     size_t i;
  1051.     try {
  1052.       for (i = 0; i < n; ++i)
  1053.         new(p + i) Fred();           // Placement new[11.10]
  1054.     } catch (...) {
  1055.       while (i-- != 0)
  1056.         (p + i)->~Fred();            // Explicit call to the destructor[11.10]
  1057.       operator delete[] (p);
  1058.       throw;
  1059.     }
  1060.     arrayLengthAssociation.insert(p, n);
  1061.  
  1062. Then the delete[] p statement becomes:
  1063.  
  1064.     // Original code: delete[] p;
  1065.     size_t n = arrayLengthAssociation.lookup(p);
  1066.     while (n-- != 0)
  1067.       (p + n)->~Fred();
  1068.     operator delete[] (p);
  1069.  
  1070. Cfront uses this technique (it uses an AVL tree to implement the associative
  1071. array).
  1072.  
  1073. Compared to the over-allocation technique[33.4], the associative array
  1074. technique is slower, but less sensitive to the problem of programmers saying
  1075. delete p rather than delete[] p.  For example, if you make a programming error
  1076. by saying delete p where you should have said delete[] p, only the first Fred
  1077. in the array gets destructed, but the heap may survive (unless you've replaced
  1078. operator delete[] with something that doesn't simply call operator delete, or
  1079. unless the destructors for the other Fred objects were necessary).
  1080.  
  1081. ==============================================================================
  1082.  
  1083. [33.6] If name mangling was standardized, could I link code compiled with
  1084.        compilers from different compiler vendors? [UPDATED!]
  1085.  
  1086. [Recently reworded and added v-table and v-pointer references[20.3] (on
  1087. 11/96).]
  1088.  
  1089. Short answer: Probably not.
  1090.  
  1091. In other words, some people would like to see name mangling standards
  1092. incorporated into the proposed C++ ANSI standards in an attempt to avoiding
  1093. having to purchase different versions of class libraries for different compiler
  1094. vendors.  However name mangling differences are one of the smallest differences
  1095. between implementations, even on the same platform.
  1096.  
  1097. Here is a partial list of other differences:
  1098.  * Number and type of hidden arguments to member functions.
  1099.    - is this handled specially?
  1100.    - where is the return-by-value pointer passed?
  1101.  * Assuming a v-table[20.3] is used:
  1102.    - what is its contents and layout?
  1103.    - where/how is the adjustment to this made for multiple and/or virtual
  1104.      inheritance?
  1105.  * How are classes laid out, including:
  1106.    - location of base classes?
  1107.    - handling of virtual base classes?
  1108.    - location of v-pointers[20.3], if they are used at all?
  1109.  * Calling convention for functions, including:
  1110.    - where are the actual parameters placed?
  1111.    - in what order are the actual parameters passed?
  1112.    - how are registers saved?
  1113.    - where does the return value go?
  1114.    - does caller or callee pop the stack after the call?
  1115.    - special rules for passing or returning structs or doubles?
  1116.    - special rules for saving registers when calling leaf functions?
  1117.  * How is the run-time-type-identification laid out?
  1118.  * How does the runtime exception handling system know which local objects need
  1119.    to be destructed during an exception throw?
  1120.  
  1121. ==============================================================================
  1122.  
  1123. [33.7] GNU C++ (g++) produces big executables for tiny programs; Why?
  1124.  
  1125. libg++ (the library used by g++) was probably compiled with debug info (-g).
  1126. On some machines, recompiling libg++ without debugging can save lots of disk
  1127. space (approximately 1 MB; the down-side: you'll be unable to trace into libg++
  1128. calls).  Merely strip-ping the executable doesn't reclaim as much as
  1129. recompiling without -g followed by subsequent strip-ping the resultant a.out's.
  1130.  
  1131. Use size a.out to see how big the program code and data segments really are,
  1132. rather than ls -s a.out which includes the symbol table.
  1133.  
  1134. ==============================================================================
  1135.  
  1136. [33.8] Is there a yacc-able C++ grammar?
  1137.  
  1138. There used to be a yacc grammar that was pretty close to C++.  As far as I am
  1139. aware, it has not kept up with the evolving C++ standard.  For example, the
  1140. grammar doesn't handle templates, "exceptions", nor
  1141. run-time-type-identification, and it deviates from the rest of the language in
  1142. some subtle ways.
  1143.  
  1144. It is available at http://srawgw.sra.co.jp/.a/pub/cmd/c++grammar2.0.tar.gz
  1145.  
  1146. ==============================================================================
  1147.  
  1148. [33.9] What is C++ 1.2? 2.0? 2.1? 3.0?
  1149.  
  1150. These are not versions of the language, but rather versions of cfront, which
  1151. was the original C++ translator implemented by AT&T.  It has become generally
  1152. accepted to use these version numbers as if they were versions of the language
  1153. itself.
  1154.  
  1155. Very roughly speaking, these are the major features:
  1156.  * 2.0 includes multiple/virtual inheritance and pure virtual[22.4] functions
  1157.  * 2.1 includes semi-nested classes and delete[] pointerToArray
  1158.  * 3.0 includes fully-nested classes, templates and i++ vs. ++i
  1159.  * 4.0 will include exceptions
  1160.  
  1161. ==============================================================================
  1162.  
  1163. SECTION [34]: Miscellaneous technical issues
  1164.  
  1165.  
  1166. [34.1] Why can't the compiler find my header file in #include "c:\test.hpp" ?
  1167.  
  1168. Because "\t" is a tab character.
  1169.  
  1170. You should use forward slashes ("/") rather than backslashes ("\") in your
  1171. #include filenames, even on an operating system that uses backslashes such as
  1172. DOS, Windows, OS/2, etc.  For example:
  1173.  
  1174.     #if 1
  1175.       #include "/version/next/alpha/beta/test.hpp"    // RIGHT!
  1176.     #else
  1177.       #include "\version\next\alpha\beta\test.hpp"    // WRONG!
  1178.     #endif
  1179.  
  1180. Note that you should use forward slashes ("/") on all your filenames[15.10],
  1181. not just on your #include files.
  1182.  
  1183. ==============================================================================
  1184.  
  1185. [34.2] Does C++ have new scoping rules for for loops?
  1186.  
  1187. Yep.
  1188.  
  1189. The following code used to be legal, but not any more, sinc i's scope is now
  1190. inside the for loop only:
  1191.  
  1192.     for (int i = 0; i < 10; ++i) {
  1193.       // ...
  1194.       if ( /* something wierd */ )
  1195.         break;
  1196.       // ...
  1197.     }
  1198.  
  1199.     if (i != 10) {
  1200.       // We exited the loop early; handle this situation separately
  1201.       // ...
  1202.     }
  1203.  
  1204. Unless you use a for loop variable after the for loop, the new scoping rule
  1205. won't break your code.  If it does break your code, in most cases the compiler
  1206. will give you a compile-time error message such as "Variable i is not in
  1207. scope".
  1208.  
  1209. Unfortunately it is possible that this new rule will silently cause your code
  1210. to do the wrong thing.  For example, if you have a global variable i, the above
  1211. code if (i != 10) silently change in meaning from the for loop variable i under
  1212. the old rule to the global variable i under the new rule.  This is not good.
  1213. If you're concerned, you should check with your compiler to see if it has some
  1214. option that forces it to use the old rules with your old code.
  1215.  
  1216. Note: You should avoid having the same variable name nested scopes, such as a
  1217. global i and a local i.  In fact, you should avoid globals althogether whenever
  1218. you can.  If you abided by these coding standards in your old code, you won't
  1219. be hurt by the new scoping rules for for loop variables.
  1220.  
  1221. ==============================================================================
  1222.  
  1223. [34.3] Why can't I overload a function by its return type?
  1224.  
  1225. If you declare both char f() and float f(), the compiler gives you an error
  1226. message, since calling simply f() would be ambiguous.
  1227.  
  1228. ==============================================================================
  1229.  
  1230. [34.4] What is "persistence"? What is a "persistent object"?
  1231.  
  1232. A persistent object can live after the program which created it has stopped.
  1233. Persistent objects can even outlive different versions of the creating program,
  1234. can outlive the disk system, the operating system, or even the hardware on
  1235. which the OS was running when they were created.
  1236.  
  1237. The challenge with persistent objects is to effectively store their member
  1238. function code out on secondary storage along with their data bits (and the data
  1239. bits and member function code of all member objects, and of all their member
  1240. objects and base classes, etc).  This is non-trivial when you have to do it
  1241. yourself.  In C++, you have to do it yourself.  C++/OO databases can help hide
  1242. the mechanism for all this.
  1243.  
  1244. ==============================================================================
  1245.  
  1246. [34.5] Why is floating point so inaccurate? Why doesn't this print 0.43?
  1247.  
  1248.     #include <iostream.h>
  1249.  
  1250.     main()
  1251.     {
  1252.       float a = 1000.43;
  1253.       float b = 1000.0;
  1254.       cout << a - b << '\n';
  1255.     }
  1256.  
  1257. (On one C++ implementation, this prints 0.429993)
  1258.  
  1259. Disclaimer: Frustration with rounding/truncation/approximation isn't really a
  1260. C++ issue; it's a computer science issue.  However, people keep asking about it
  1261. on comp.lang.c++, so what follows is a nominal answer.
  1262.  
  1263. Answer: Floating point is an approximation.  The IEEE standard for 32 bit float
  1264. supports 1 bit of sign, 8 bits of exponent, and 23 bits of mantissa.  Since a
  1265. normalized binary-point mantissa always has the form 1.xxxxx... the leading 1
  1266. is dropped and you get effectively 24 bits of mantissa.  The number 1000.43
  1267. (and many, many others) is not exactly representable in float or double format.
  1268. 1000.43 is actually represented as the following bitpattern (the "s" shows the
  1269. position of the sign bit, the "e"s show the positions of the exponent bits, and
  1270. the "m"s show the positions of the mantissa bits):
  1271.  
  1272.         seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm
  1273.         01000100011110100001101110000101
  1274.  
  1275. The shifted mantissa is 1111101000.01101110000101 or 1000 + 7045/16384.  The
  1276. fractional part is 0.429992675781.  With 24 bits of mantissa you only get about
  1277. 1 part in 16M of precision for float.  The double type provides more precision
  1278. (53 bits of mantissa).
  1279.  
  1280. ==============================================================================
  1281.  
  1282. SECTION [35]: Miscellaneous environmental issues
  1283.  
  1284.  
  1285. [35.1] Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  1286.  
  1287. Yes, here are three (the first prevents line breaks between the C and "++"):
  1288.  
  1289.     \def\CC{{C\nolinebreak[4]\hspace{-.05em}\raisebox{.4ex}{\tiny\bf ++}}}
  1290.  
  1291.     \def\CC{C\raise.22ex\hbox{{\footnotesize +}}\raise.22ex\hbox{\footnotesize +}}
  1292.  
  1293.     \def\CC{{C\hspace{-.05em}\raisebox{.4ex}{\tiny\bf ++}}}
  1294.  
  1295. ==============================================================================
  1296.  
  1297. [35.2] Are there any pretty-printers that reformat C++ source code?
  1298.  
  1299. In alphabetical order:
  1300.  * C++2LaTeX is a LaTeX pretty printer.  It is available via ftp from
  1301.    ftp://ftp.germany.eu.net/pub/packages/TeX/support/pretty/C++2LaTeX-3.02.tar.gz
  1302.  * C-Clearly by V Communications, Inc. is a Windows program that comes with
  1303.    standard formatting templates and also allows you to customize your own.
  1304.    http://www.v-com.com/
  1305.  * GNU indent program may help.  It's somewhere on ftp://www.cygnus.com [Note:
  1306.    If anyone has a better URL, please let me know (cline@parashift.com).]
  1307.  * tgrind is a Unix based pretty printer.  It usually comes with the public
  1308.    distribution of TeX and LaTeX in the directory
  1309.    "...tex82/contrib/van/tgrind".  A more up-to-date version of tgrind by Jerry
  1310.    Leichter can be found on: ftp://venus.ycc.yale.edu/pub in [.TGRIND].  [Note:
  1311.    If anyone has an updated URL for tgrind, please let me know
  1312.    (cline@parashift.com).]
  1313.  
  1314. ==============================================================================
  1315.  
  1316. [35.3] Is there a C++-mode for GNU emacs? If so, where can I get it?
  1317.  
  1318. Yes, there is a C++-mode for GNU emacs.
  1319.  
  1320. The latest and greatest version of C++-mode (and C-mode) is implemented in the
  1321. file cc-mode.el.  It is an extension of Detlef and Clamen's version.  A version
  1322. is included with emacs.  Newer version are available from the elisp archives.
  1323.  
  1324. ==============================================================================
  1325.  
  1326. [35.4] Where can I get OS-specific questions answered (e.g., BC++, DOS,
  1327.        Windows, etc)? [UPDATED!]
  1328.  
  1329. [Recently added Borland C++ URLs thanks to Simon Edlund (on 1/97).]
  1330.  
  1331. See one of the following:
  1332.  * MS-DOS issues: comp.os.msdos.programmer
  1333.  * MS-Windows issues: comp.windows.ms.programmer
  1334.  * Unix issues: comp.unix.programmer
  1335.  * Borland C++ issues (e.g., OWL, BC++ compiler bugs, general C++ concepts,
  1336.    windows programming):
  1337.    - Using your Web browser: http://www.cs.rpi.edu/~wiseb/owl-list/
  1338.    - To get on the mailing list: send an e-mail message with the word
  1339.      "SUBSCRIBE" in the Subject: line to majordomo@netlab.cs.rpi.edu
  1340.    - To get the FAQ:
  1341.      ftp://ftp.netlab.cs.rpi.edu/pub/lists/owl-list-faq/drafts/owl_faq.hlp
  1342.  
  1343. ==============================================================================
  1344.  
  1345. [35.5] Why does my DOS C++ program says "Sorry: floating point code not
  1346.        linked"?
  1347.  
  1348. The compiler attempts to save space in the executable by not including the
  1349. float-to-string format conversion routines unless they are necessary, but
  1350. sometimes it guesses wrong, and gives you the above error message.  You can fix
  1351. this by (1) using <iostream.h> instead of <stdio.h>, or (2) by including the
  1352. following function somewhere in your compilation (but don't call it!):
  1353.  
  1354.     static void dummyfloat(float *x) { float y; dummyfloat(&y); }
  1355.  
  1356. See FAQ on stream I/O for more reasons to use <iostream.h> vs. <stdio.h>.
  1357.  
  1358. ==============================================================================
  1359.  
  1360. [35.6] Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
  1361.  
  1362. If you're using BC++ for a Windows app, and it works OK as long as you have the
  1363. BC45 IDE running, but when the BC45 IDE is shut down you get an exception
  1364. during the creation of a window, then add the following line of code to the
  1365. InitMainWindow() member function of your application
  1366. (YourApp::InitMainWindow()):
  1367.  
  1368.     EnableBWCC(TRUE);
  1369.  
  1370. ==============================================================================
  1371.  
  1372.